package com.smile.frame.config.rabbit.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.smile.frame.config.rabbit.enums.IBindEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;

import java.util.UUID;

/**
 * @author LGC
 */
@Slf4j
@AllArgsConstructor
public class RabbitUtil {

    private final RabbitTemplate rabbitTemplate;

    /**
     * 发送普通消息
     *
     * @param bindEnum
     * @param msg
     */
    public void send(IBindEnum bindEnum, Object msg) {
        log.info("message to MQ bind:{},msg:{}", bindEnum, JSONUtil.toJsonStr(msg));
        /**
         * 消息默认是持久化的
         * message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
         */
        rabbitTemplate.convertAndSend(bindEnum.getExchange(), bindEnum.getKey(), msg, new CorrelationData(IdUtil.fastUUID()));
    }

    /**
     * 发送延时消息
     *
     * @param bindEnum
     * @param msg
     * @param second
     */
    public void sendDelay(IBindEnum bindEnum, Object msg, Integer second) {
        log.info("message to MQ bind:{},delayTime:{},msg:{}", bindEnum, second, JSONUtil.toJsonStr(msg));
        rabbitTemplate.convertAndSend(bindEnum.getExchange(), bindEnum.getKey(), msg,
                message -> {
                    message.getMessageProperties().setDelay(second * 1000);
                    return message;
                }, new CorrelationData(IdUtil.fastUUID()));
    }


}
